<!-- 添加素材弹窗 -->
<template>
    <div>
        <CommonDialog 
            :visible="props.visible" 
            width="680px" 
            :title="'编辑'+ tips.file" 
            @on-close="cancel"
            @on-confirm="save"
            :show-footer="true"
        >
            <el-form ref="formRef" :model="formData" :rules="formRule" v-loading="loading">
                <el-form-item prop="contentId" class="btn-form">
                     <!-- 视频资源 -->
                     <div>
                        <div class="video-file-wrapper">
                           <div v-if="formData.materialVO?.materialId && (contentType === 'video' || contentType === 'audio')">
                               <div class="video-wrapper">
                                   <Video ref="videoRef" :player-id="`player-${formData.materialVO?.materialId}`" :video-data="formData.materialVO" :isReport="false" :videoConfig="fmtVideoConfig()" height="90px" @set-duration="setDuration"/>
                               </div>
                           </div>
                           <div class="file-wrapper" v-if="formData.materialVO?.materialId && contentType !== 'video' && contentType !== 'audio'">
                               <div class="tag" :class="[formData.materialVO?.materialType]">{{formData.materialVO?.materialFullName}}</div>
                               <div class="size">{{formData.materialVO?.materialSizeFormat}}</div>
                           </div>
                           <el-button class="srt-el-button srt-el-button--link srt-el-button-h28 add-btn" @click="handleAdd">{{formData.materialVO?.materialId ? '更换' : '添加'}}{{tips.file}}</el-button>
                        </div>
                        <div class="time" v-if="formData.materialVO?.materialId && (contentType === 'video' || contentType === 'audio') && formData.unitValue">时长：{{fmtTime(formData.unitValue)}}</div>
                    </div>
                </el-form-item>
                <el-form-item :label="tips.title" prop="contentTitle" class="srt-el-input-item" :label-width="labelWidth">
                    <el-input show-word-limit maxlength="50" type="text" v-model="formData.contentTitle" class="srt-el-input"
                        placeholder="请输入标题，最多50个字" style="width: 450px;">
                    </el-input>
                </el-form-item>
                <el-form-item label="文档长度" prop="unitValue" class="srt-el-input-item input-form" v-if="contentType === 'text'" :label-width="labelWidth">
                    <!-- <el-select v-model="formData.unit" class="srt-select input-select"
                            placeholder="请选择" popper-class="srt-select-popper" @change="formData.unitValue = ''">
                            <el-option key="1" label="按时长"
                                :value="1" />
                            <el-option key="2" label="按页数"
                                :value="2" />
                    </el-select> -->
                    <el-input type="text" v-model="formData.unitValue" class="srt-el-input input-number"
                        placeholder="请输入时长">
                    </el-input>
                    <span class="mar-l10">分钟</span>
                    <span class="content-tip" v-if="contentType === 'text'">预估阅读学习文档所需的时间</span>
                </el-form-item>
                <el-form-item label="添加字幕" prop="subtitle" class="srt-el-input-item" v-if="formData.materialVO && formData.materialVO.materialType === 'video' && formData.materialVO.materialId" :label-width="labelWidth">
                    <UploadSubmit :subtitle-obj="formData.subtitle" :material-id="formData.materialVO?.materialId" @update-subtitle="updateSubTitle"></UploadSubmit>
                </el-form-item>
            </el-form>
        </CommonDialog>
        <!-- 素材库 isForciblySelect-->
        <yanxiu-material-dialog
            class="yanxiu-material-dialog-wrap"
            v-model="addVisible"
            :category="materialConfig.category"
            :mode="1"
            :limitType="materialConfig.limitType"
            :limitSize="listSize"
            previewEnable
            showMyMaterial
            @on-ok="fileInsert"
        />
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue"
import CommonDialog from '@/components/common-dialog.vue';
import YanxiuMaterialDialog from '@/components/yanxiu-material-dialog.vue';
import Video from '@/views/catalogue-detail/part/video-cell.vue'; // 视频
import UploadSubmit from '@/views/design/part/upload-subtitle.vue';
import { deepCopy, queryToJson, Debounce } from '@/lib/tools';
import { useRoute } from 'vue-router'
import XgPlayer from '@/components/.xgplayer/xgplayer.js';
import { fmtTransTime } from '@/lib/biz-tools.js'
const route = useRoute()

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    catalogueData: {
        type: Object,
        default: () => {
            return {};
        } 
    },
    form: {
        type: Object,
        default: () => {
            return {};
        }
    },
    type: {
        type: String,
        default: ''
    },
    initSubTitleMap: { // 初始化字幕信息
        type: Object,
        default: () => {
            return {};
        } 
    }
})

const emit = defineEmits(['update:visible', 'update-tree-after-edit']);

// 字幕信息
const subTitleMap = ref({});

const formRef = ref(null);

const loading = ref(false);

const videoRef = ref(null);

// 表单校验
const formRule = ref({
    contentTitle: [
    {
            required: true,
            validator: (rule, value, callback) => {
                let temp = value && value.trim() || '';
                if (temp.length > 50 || temp.length < 2) {
                    callback('请输入2-50个字的标题');
                }else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    contentId: [
        { required: true, message: props.catalogueData.tag === 'text' ? '请选择文档' : '请选择音视频', trigger: 'none'}
    ],
    unitValue: [
        {
            required: true,
            validator: (rule, value, callback) => {
                let temp = Number(value);
                if (!/^[0-9]+(.[0-9]{1})?$/.test(temp) || temp > 120 || temp < 0.5) {
                    callback('请输入0.5-120之间的数，最多1位小数');
                } else if(!temp){
                    callback(new Error('请输入学习时长'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
});

// 表单对象
const formData = ref({
    unit: 1
})

const tipsMap = {
    'video': {
        title: '音视频标题',
        file: '音视频'
    },
    'text': {
        title: '文档标题',
        file: '文档'
    }
}

// 提示语
const tips = computed(() => {
    let key = (props.catalogueData.tag === 'video' || props.catalogueData.tag === 'audio') ? 'video' : 'text';
    return tipsMap[key];
})

const contentType = computed(() => {
    return (props.catalogueData.tag === 'video' || props.catalogueData.tag === 'audio') ? props.catalogueData.tag : 'text';
})

const labelWidth = computed(() => {
    return (props.catalogueData.tag === 'video' || props.catalogueData.tag === 'audio') ? 98 : 80;
})

// 素材库限制大小
const listSize = {
    document: 1 * 500 * 1024 * 1024,
    video: 2 * 1024 * 1024 * 1024,
    audio:  1 * 100 * 1024 * 1024,

}

// 素材类型
const materialConfig = computed(() => {
    if(props.catalogueData.tag === 'video' || props.catalogueData.tag === 'audio') { // 视频类型
        return {
            category: ['video', 'audio'],
            limitType: {
                video: ['wmv', 'avi', 'mp4', 'mov', 'flv'],
                audio: ['mp3', 'wma', 'flac', 'm4a', 'ogg', 'ape', 'amr', 'wav', 'aac', 'aiff', 'caf']
            },
        }
    }
    return {
        category: ['document'],
        limitType: {
            document: ['doc', 'docx', 'ppt', 'pptx', 'txt', 'xls', 'xlsx', 'pdf', 'rtf', 'odt'],
        }
     }
})


// 素材库对话框
const addVisible = ref(false);

// 选择素材
async function fileInsert(fileList) {
    if (!fileList[0]) {
        return;
    }
    if (fileList[0].materialId && fileList[0].materialType === 'video') {
        // formData.value.subtitle = null;
        await getSubTitleList(fileList[0].materialId);
        // console.log(subTitleMap.value, 'subTitleMap.value', fileList[0].materialId);
        formData.value.subtitle = subTitleMap.value[fileList[0].materialId] ? subTitleMap.value[fileList[0].materialId] : null;
    }
    formData.value.materialVO = fileList[0];
    formData.value.contentId = fileList[0].materialId;
    formData.value.unitValue = fileList[0].duration;
    formData.value.contentTitle = fileList[0].materialName;
    if(contentType.value === 'video' || contentType.value === 'audio') {
        videoRef.value && videoRef.value.destroyVideo();
        await nextTick();
        setTimeout(() => {
            videoRef.value && videoRef.value.initPlayer();
        }, 100)
    }
}

// 添加视频
function handleAdd() {
    addVisible.value = true;
}

function setDuration(obj) {
    formData.value.unitValue = formData.value.unitValue || obj.duration;
}

// controls: false 关闭控制条 播放器控制条由播放/暂停、定位、音量、全屏切换等元素组成
function fmtVideoConfig() {
    return {volume: 0, autoplay: formData.value.materialVO?.materialType === 'audio', controlsList: ['nofullscreen'], controls: false}
}

// 格式化时间
function fmtTime(val = 0) {
    return fmtTransTime(val);
}

function cancel () {
    formData.value.materialVO = null; // 作用是关闭视频
    emit('update:visible', false);
}

function save () {
    formRef.value.validate((valid) => {
        if(!valid) {
            return;
        }
        if(!formData.value.unitValue && (contentType.value === 'video' || contentType.value === 'audio')) {
            G_dispatchEvent('toast', { message: '请等待音视频加载结束后点击保存', type: 'error'});
            return;
        }
        loading.value = true;

        let params = {
            contentTitle: formData.value.contentTitle,
            unitValue: contentType.value === 'text' && formData.value.unit === 1 ? formData.value.unitValue * 60 : formData.value.unitValue,
            contentId: formData.value.materialVO.materialId,
            unit: formData.value.unit || 1,
            tag: formData.value.materialVO.materialType,
            contentType: 'material'
        }

        if(props.catalogueData.catalogueId) {
            params.id = props.catalogueData.catalogueId;
            params.courseWareId = formData.value.courseWareId;
        }

        G_transmit('courseContentCreate', {
            data: {
                contentList: [
                    {
                        ...params
                    }
                ],
                courseId: route.params.courseId,
                pid: props.catalogueData.pid
            }
        })
        .then((res) => {
            // G_dispatchEvent('toast', { message: '编辑成功', type: 'success'});
            let newObj = Object.assign(
                {}, props.catalogueData, 
                {...params}, {catalogueName: params.contentTitle}, 
                {courseWare: {
                    contentId: formData.value.materialVO.materialId, 
                    materialVO: formData.value.materialVO,
                    unitValue: params.unitValue,
                    unit: params.unit,
                    title: params.contentTitle
                }
            })
            let deleteList = [];
            let insertList = [];
            let materialId = formData.value.materialVO.materialId;
            let subTitleMapObj = subTitleMap.value[materialId];
            // 先判断现在有没有字幕，有的话和视频字幕进行比对
            if(!formData.value.subtitle) { // 当前没字幕
                if (subTitleMapObj) {
                    deleteList.push(subTitleMapObj.subtitleId);
                }
            } else {    // 如果现在有字幕，判断和之前的一样不
                if (!formData.value.subtitle.subtitleId) { // 不存在subtitleId，说明字幕变了
                    let subtitle = formData.value.subtitle;
                    insertList.push({
                        materialId: materialId,
                        subtitleName: subtitle.nameWithoutSuffix,
                        subtitleUrl: subtitle.fullUrl,
                        subtitleSize: subtitle.size,
                        subtitleType: subtitle.name.slice(subtitle.name.lastIndexOf('.') + 1),
                        subtitleInitType: 1,
                        orderIndex: 0,
                        ispType: subtitle.ispType
                    })
                    subTitleMapObj && subTitleMapObj.subtitleId && deleteList.push(subTitleMapObj.subtitleId);
                } else if (formData.value.subtitle.subtitleId !== subTitleMapObj.subtitleId) {
                    subTitleMapObj && subTitleMapObj.subtitleId && deleteList.push(subTitleMapObj.subtitleId);
                }
            }
            // console.log(insertList, deleteList, 'insertList, deleteList');
            subtitleSave(insertList, deleteList)
            emit('update-tree-after-edit', 'update', newObj)
            cancel();
        })
        .catch((_err) => {
            console.log(_err)
        }).finally(() => {
            loading.value = false;
        });
    })
}

async function getDetail() {
    loading.value = true;
    G_transmit('courseContentDetail', {
        queries: {
            id: props.catalogueData.catalogueId
        }
    }).then(async (res) => {
        formData.value = res.data || {};
        if (formData.value.tag === 'video') {
            formData.value.subtitle = null;
        }
        subTitleMap.value = props.initSubTitleMap;
        formData.value.subtitle = formData.value.tag === 'video' && formData.value.materialVO && subTitleMap.value[formData.value.materialVO.materialId] ? subTitleMap.value[formData.value.materialVO.materialId] : null;
        if (contentType.value === 'text') { // 文档计时分两种1:按时长 2：按页数
            if (formData.value.unit === 1) {  // 前台显示分钟，后端存的是秒
                formData.value.unitValue = formData.value.unitValue/60;
            } else { // 按页数每页是10s
                formData.value.unit = 1; // 去掉了按页码计时
                let tempNum = formData.value.unitValue * 10 / 60;
                if (Math.floor(tempNum) !== tempNum) {
                    tempNum = tempNum.toFixed(1);
                }
                formData.value.unitValue = tempNum;
            }
            
        } else {
            formData.value.unitValue = formData.value.unitValue;
        }
        if (formData.value?.materialVO?.materialType === 'video' || formData.value?.materialVO?.materialType === 'audio') {
            await nextTick();
            setTimeout(() => {
                videoRef.value && videoRef.value.initPlayer();
            }, 100)
        }
    }).catch((_err) => {
        console.log(_err)
    }).finally(() => {
        loading.value = false;
    });
}

function updateSubTitle (subtitle) {
    // 原来存在字幕，字幕被删除
    if (!subtitle && formData.value.subtitle) {
        // delSubTitle
    }
    formData.value.subtitle = subtitle;
}

// 获取字幕列表 目录有视频获取字幕
function getSubTitleList (id) {
    if (id) {
        G_transmit('subtitleSearch', {
            data: {
                materialIds: [id],
                subtitleInitType: 1
            }
        }).then(async (res) => {
            subTitleMap.value = {};
            (res.data || []).forEach(item => {
                subTitleMap.value[item.materialId] = item;
                formData.value.subtitle = formData.value.materialVO && subTitleMap.value[formData.value.materialVO.materialId] ? subTitleMap.value[formData.value.materialVO.materialId] : null;
            })
        }).catch((_err) => {
            console.log(_err)
        }).finally(() => {
        })
    }
}

// 字幕保存与删除
function subtitleSave(insertList, deleteList) {
    if (insertList.length === 0 && deleteList.length === 0) {
        return
    }
    G_transmit('subtitleSave', {
        data: {
            insertList: insertList,
            deleteList: deleteList
        }
    })
    .then((res) => {
    }).catch((_err) => {
    })
}

watch(() => props.visible, (val) => {
    if (val) {
        if(props.catalogueData.catalogueId) {
            getDetail();
        }
        // formData.value = Object.assign({}, formData.value, props.form, {contentTitle: props.form.catalogueName});
    } else {
        formRef.value && formRef.value.resetFields();
    }
})
</script>

<style lang="scss">
.yanxiu-material-dialog-wrap {
    .dialog-wrap {
        z-index: 2200!important;
    }
}
 
</style>

<style lang="scss" scoped>
@mixin img-style(){
    content: '';
    width: 18px;
    height: 18px;
    display: inline-block;
    vertical-align: middle;
    transform: translateY(-1px);
    margin-right: 4px;
}
.video-wrapper {
    margin-right: 16px;
    height: 90px;
    width: 160px;
    // margin-top: 20px;
    position: relative;
    .video-player {
        height: 180px;
        width: 320px;
    }
    :deep(.xgplayer-start) {
        width: 26px !important;
        height: 26px !important;
        line-height: 26px;
        margin: -13px auto auto -13px;
        svg {
            width: 26px !important;
            height: 26px !important;
            // transform: translate(-2px, -2px);
        }
    }
    
    :deep(.xgplayer-controls) {
        height: 20px;
        .xgplayer-progress {
           height: 10px;
        }
        .xgplayer-play {
            width: 20px;
        }
        svg, .xgplayer-volume,.xgplayer-icon {
            width: 20px;
            height: 20px;
        }
        .xgplayer-volume {
            margin-right: 8px;
            .xgplayer-icon {
                bottom: -1px;
            }
        }
        .xgplayer-time {
            height: 20px;
            line-height: 22px;
            font-size: 12px;
        }
        .xgplayer-fullscreen {
            display: none;
        }
    }
}
.video-file-wrapper {
    display: flex;
    align-items: center;
    .add-btn {

    }
    .time {
        font-size: 14px;
        color: var(--srt-color-gray);
        margin-top: 12px;
        line-height: 1;
        &::before {
            content: '\e6bb';
            font-family: 'iconfont';
            margin-right: 6px;
            font-size: 16px;
            display: inline-block;
            vertical-align: middle;
            transform: translateY(-1px);
        }
    }
}
.file-wrapper {
    margin-right: 16px;
    width: 340px;
    background: #F7F9FA;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 12px 12px 14px;
    // margin-top: 20px;
    .size {
        padding-left: 24px;
        line-height: 1;
        margin-top: 10px;
        color: var(--srt-color-gray);
    }
    .tag {
        font-size: 14px;
        color: var(--srt-main-text-color);
        overflow: hidden;
        line-height: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        &.doc, &.docx {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/doc.png') no-repeat;
                background-size: contain;
            }
        }
        &.ppt, &.pptx {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/ppt.png') no-repeat;
                background-size: contain;
            }
        }
        &.xls, &.xlsx{
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/excel.png') no-repeat;
                background-size: contain;
            }
        }
        &.pdf {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/pdf.png') no-repeat;
                background-size: contain;
            }
        }
        &.files {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/files.png') no-repeat;
                background-size: contain;
            }
        }
        &.rest,
        &.unknown {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/rest.png') no-repeat;
                background-size: contain;
            }
        }
    }
}
.mar-l10 {
    margin-left: 10px;
    color: var(--srt-main-text-color);
}
.content-tip {
    font-size: 14px;
    color: var(--srt-color-gray);
    margin-left: 12px;
    &::before {
        content: '\e70e';
        font-family: 'iconfont';
        margin-right: 6px;
        font-size: 16px;
        vertical-align: bottom;
    }
}
.input-number {
    width: 220px;
}
</style>

